// pages/myCart/myCart.js
Page({

   /**
    * 页面的初始数据
    */
   data: {
      clickItem: [], //被点击的单个数据
      allClickItem: [], //点击的数据集合
      mendianList: [],
      myAddress: {
         name: '南京市新街口明瓦廊146号',
         distance: 0
      },
      isshow: false, //元素是否显示
      count: 0, //默认数量
      isSelectAll: true,
      total: 0,
      checkedCount: 0,
   },
   //长按删除一条数据
   deleteItem: function(e) {
      let that = this
      // 输出所有allclickItem 
      console.log("输出所有allclickItem ")
      console.log(that.data.allClickItem)
      console.log(e)
      //獲取被点击的item的下标
      var index = e.currentTarget.dataset.id; //获取当前长按图片下标
      wx.showModal({
         title: '提示',
         content: '确定要删除这一杯茶喵喵吗？',
         success: function(res) {
            if (res.confirm) {
               console.log('点击确定了');
               // images.splice(index, 1);
               that.data.allClickItem.splice(index, 1)
            } else if (res.cancel) {
               console.log('点击取消了');
               return false;
            }
            //更新底部的按钮和就算数量和合计金额
            that.calcTotal()

            that.setData({
               allClickItem: that.data.allClickItem,
               count: that.data.count,
               total: that.data.total,
            });
            console.log("长按更新后的allclickItem ")
            console.log(that.data.allClickItem)
         }
      })
   },


   // 点击结算
   jiesuan: function(e) {
      let that = this

      wx.showToast({
         title: '加载中',
         icon: "loading",
         duration: 1000,
         success: function() {
            setTimeout(function() {
               //把allClickItem存到本地
               wx.setStorage({
                  key: "allClickItem",
                  data: that.data.allClickItem
               })
               //allClickItem清空页面上的数组 allClickItem
               // 先不清空  防止不支付

               that.setData({
                  allClickItem: []
               })

               wx.navigateTo({
                  url: '../myConfirmOrder/myConfirmOrder',
               })
            }, 1000)
         }
      })




      // wx.showToast({
      //    title: '免密支付中',
      //    icon: 'loading',
      //    duration: 3000,
      //    success: function() {
      //       setTimeout(function() {
      //          wx.showToast({
      //             title: '支付成功',
      //             icon: 'success',
      //             duration: 3000,
      //             success: function() {
      //                setTimeout(function() {
      //                   wx.switchTab({
      //                      url: '../myOrder/myOrder'
      //                   })
      //                }, 2000)
      //                wx.removeStorage({
      //                   key: 'clickItem',
      //                   success: function(res) {
      //                      that.setData({
      //                         clickItem: '',
      //                         allClickItem: '',
      //                      })
      //                   },
      //                })
      //             }
      //          })
      //          //要延时执行的代码
      //       }, 2000) //延迟时间 
      //    }
      // })

   },
   chooseAll: function(e) {
      let that = this
      that.data.isSelectAll = !that.data.isSelectAll
      //循环判断   若全选是true   则给所有按钮的checked设置为true 
      //循环判断   若全选是false  则给所有按钮的checked设置为false 
      if (that.data.allClickItem == '') {
         // wx.showToast({
         //    title: '购物车为空',
         //    icon:'loading',
         //    duration: 1000
         // })
      } else {
         that.data.allClickItem.forEach((r1) => {
            if (that.data.isSelectAll == false) {
               that.data.allClickItem.forEach((r2) => {
                  r2.checked = false
               })
            } else if (that.data.isSelectAll == true) {
               r1.checked = true
            }
         })
      }

      that.setData({
         allClickItem: that.data.allClickItem,
         isSelectAll: that.data.isSelectAll
      })
      that.calcTotal(); //调用计算的方法
   },
   //计算总价
   calcTotal: function() {
      console.log("总价变化")
      let that = this

      // console.log("111111111111111111111111111")
      // console.log(that.data.checkedCount)

      that.data.total = 0;
      that.data.checkedCount = 0
      if (that.data.allClickItem == '') {
         // wx.showToast({
         //    title: '购物车为空',
         //    icon:"loading",
         //    duration:1000
         // })
      } else {
         that.data.allClickItem.forEach((r) => {

            if (r.checked) {
               that.data.checkedCount++; //数量选中个数加1
               that.data.total += r.num * r.price //加价格
            }
         })
      }

      //如果有一个没有选中 有一个不为true 全选按钮改成false

      //如果按钮全部选中  全都为true       全选按钮改成true
      if (that.data.checkedCount === that.data.allClickItem.length) {
         that.data.isSelectAll = true
      } else if (that.data.checkedCount != that.data.allClickItem.length) {
         that.data.isSelectAll = false
      }
      that.setData({
         total: that.data.total,
         checkedCount: that.data.checkedCount,
         isSelectAll: that.data.isSelectAll
      })
      //判断全选

   },
   //changeState  改变选中状态
   changeState: function(e) {
      let that = this
      // console.log(e.currentTarget.dataset.id)
      var obj = this.data.allClickItem.find(r => r.id === e.currentTarget.dataset.id)
      obj.checked = !obj.checked
      that.setData({
         allClickItem: that.data.allClickItem
      })


      that.calcTotal(); //调用计算的方法
   },
   // 减  
   low: function(e) {
      let that = this
      console.log(e)
      let index = e.currentTarget.dataset.id //獲取点击的该item的下标
      console.log("下标" + index)
      let thisClick = that.data.allClickItem[index].num //获取点击的item的num
      if (that.data.allClickItem[index].num <= 1) {
         that.setData({
            thisClick: 1,
            allClickItem: that.data.allClickItem
         })
         console.log("--------------------")
         wx.showToast({
            title: '不能再少了哦！',
            icon: 'none',
            duration: 1000
         })
      } else {
         that.setData({
            thisClick: that.data.allClickItem[index].num--,
            allClickItem: that.data.allClickItem
         })
      }

      console.log("item.num=" + that.data.allClickItem[index].num)


      that.calcTotal(); //调用计算的方法
   },
   //加
   upper: function(e) {
      let that = this
      console.log(e)
      let index = e.currentTarget.dataset.id //獲取点击的该item的下标
      console.log("下标" + index)
      let thisClick = that.data.allClickItem[index].num //获取点击的item的num
      // console.log("item.num=" + thisClick)
      that.setData({
         thisClick: ++that.data.allClickItem[index].num,
         allClickItem: that.data.allClickItem
      })
      console.log("item.num=" + that.data.allClickItem[index].num)


      that.calcTotal() //调用计算的方法
   },


   ///自提 外卖
   changewuliutype() {
      this.setData({
         isziti: !this.data.isziti
      })
   },
   /**
    * 生命周期函数--监听页面加载
    */
   onLoad: function(options) {
      let that = this

      //获取goodsList
      wx.request({
         url: 'https://www.easy-mock.com/mock/5d257e0d77744b2808b8840d/study/chaMiaoMiaoGoodsList',
         success: function(res) {
            console.log(res)
            that.setData({
               goodsList: res.data
            })
         }
      })


      //定位
      wx.getLocation({
         type: "gcj02",
         success: function(res) {
            //获取门店的地址
            wx.request({
               url: 'https://apis.map.qq.com/ws/geocoder/v1/',
               data: {
                  // address: "南京市新街口明瓦廊146号",
                  address: that.data.myAddress,
                  key: "J3LBZ-ERWCU-RX4VX-2NUQQ-NOBY5-2VFGJ"
               },
               success: function(resOne) {
                  console.log(resOne)
                  console.log(resOne.data.result.location)
                  // 获取我自己的位置
                  wx.request({
                     url: 'https://apis.map.qq.com/ws/distance/v1/?parameters',
                     data: {
                        key: "J3LBZ-ERWCU-RX4VX-2NUQQ-NOBY5-2VFGJ",
                        from: `${res.latitude},${res.longitude}`,
                        to: resOne.data.result.location.lat + "," + resOne.data.result.location.lng,
                        mode: "driving"
                     },
                     success: function(resTwo) {
                        console.log(resTwo.data.result.elements[0].distance) //距离
                        that.data.myAddress.distance = resTwo.data.result.elements[0].distance
                        that.setData({
                           myAddress: that.data.myAddress
                        })
                     }
                  })
               }
            })

         }
      })





      that.calcTotal(); //调用计算的方法
      that.setData({
         allClickItem: that.data.allClickItem,
         count: that.data.count,
         total: that.data.total,
      });
   },

   /**
    * 生命周期函数--监听页面初次渲染完成
    */
   onReady: function() {
      // let that = this
      // that.calcTotal(); //调用计算的方法
   },

   /**
    * 生命周期函数--监听页面显示
    */
   onShow: function() {

      let that = this

      // if(){
      // }

      wx.getStorage({
         key: 'clickItem',
         success: function(res) {
            that.setData({
               clickItem: res.data,
               isshow: true
            })
            console.log("**************输出被点击的单个数据*************")
            console.log(that.data.clickItem)
            console.log(res.data)
            //给所有数据追加数据
            // var myallClickItem = that.data.allClickItem.concat(res.data)
            // myallClickItem = JSON.stringify(myallClickItem)
            that.setData({
               allClickItem: that.data.allClickItem.concat(res.data),
               // allClickItem: myallClickItem
            })
            console.log("********所有数据***********")
            console.log(that.data.allClickItem)
         },
         fail: function(res) {
            wx.showToast({
               title: '加载中...',
               icon: "loading",
               duration: 1000
            })
         }
      })
      wx.removeStorage({
         key: 'clickItem',
         success(res) {
            console.log("已成功移除缓存clickItem")
         }
      })


      that.calcTotal(); //调用计算的方法
      that.setData({
         allClickItem: that.data.allClickItem,
         count: that.data.count,
         total: that.data.total,
      });
   },

   /**
    * 生命周期函数--监听页面隐藏
    */
   onHide: function() {

   },

   /**
    * 生命周期函数--监听页面卸载
    */
   onUnload: function() {

   },

   /**
    * 页面相关事件处理函数--监听用户下拉动作
    */
   onPullDownRefresh: function() {

   },

   /**
    * 页面上拉触底事件的处理函数
    */
   onReachBottom: function() {

   },

   /**
    * 用户点击右上角分享
    */
   onShareAppMessage: function() {

   }
})